import os
import subprocess
from IPy import IP

class Empty_Error(Exception):
    pass

def reachable_test(ip_address):
    for temp in ip_address:
        # print(type(temp))
        # break
        if os.name == 'nt':
            if subprocess.call(['ping', '-n', '1', str(temp)]) == 0:
                reach_list.append(temp)

            else:
                unreach_list.append(temp)

        elif os.name == 'posix':
            if subprocess.call(['ping', '-c', '1', str(temp)]) == 0:
                reach_list.append(temp)

            else:
                unreach_list.append(temp)

def file_write(list1, list2):
    with open("reachable.txt", 'w', encoding='GBK') as f1:
        for temp in list1:
            f1.write(f"{temp} 已被使用\n")

        f1.close()

    with open("unreachable.txt", 'w', encoding='GBK') as f2:
        for temp in list2:
            f2.write(f"{temp} 未被使用\n")

        f2.close()
def main():
    try:
        get_input = input("请输入一个IP地址或网段 ：")
        ip = IP(get_input)
        if len(ip) == 0:
            raise Empty_Error("输入的网址或网段为空！请检查后重新输入")

    except ValueError as ve:
        print("请正确输入IP地址或者网段！", ve)

    reachable_test(ip)
    file_write(reach_list, unreach_list)


reach_list, unreach_list = [], []
main()

